package com.mycar2w.cloud.web.controller;

import com.mycar2w.cloud.entity.ApplieOrder;
import com.mycar2w.cloud.service.pojo.TransactionPost;
import com.mycar2w.cloud.service.repository.ApplieOrderRepository;
import com.mycar2w.cloud.service.serviceimpl.MasterService;
import com.mycar2w.cloud.web.util.ReturnModelAndView;
import com.umuw.cloud.core.util.JsonEntity;
import com.umuw.cloud.core.util.ReturnUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * created time 2017/3/25
 *
 * @author ljc
 * @version V1.0
 */
@RestController
@RequestMapping("/masters")
public class MasterController extends MycarBaseConTroller{
    @Autowired
    private MasterService masterService;
    @Autowired
    private ApplieOrderRepository applieOrderRepository;



    @RequestMapping(value = "/master",method = RequestMethod.GET)
    public ModelAndView findApplieOrder(){
        getMaster();
        return ReturnModelAndView.returnSuccess("masterManager");
    }
    @RequestMapping(value = "/applies_order_list",method = RequestMethod.GET)
    public ModelAndView findApplieOrders(@RequestParam Integer category,@RequestParam(defaultValue = "0") Integer pageIndex){
        getMaster();
        List<ApplieOrder> applieOrders=masterService.findAppliOrders(category,pageIndex);
        return ReturnModelAndView.returnSuccess("applie_order_list",applieOrders);
    }
    @RequestMapping(value = "/applie_order",method = RequestMethod.GET)
    public ModelAndView findOrders(@RequestParam Long applieOrderId){
        getMaster();
        ApplieOrder applieOrder=masterService.findApplieOrder(applieOrderId);
        return ReturnModelAndView.returnSuccess("applie_order",applieOrder);
    }
    @RequestMapping(value = "/applie_order_update",method = RequestMethod.POST)
    public ModelAndView updateOrderStatus(@RequestParam Long nowApplieOrderId,@RequestParam Integer category){
        getMaster();
        ApplieOrder applieOrder=applieOrderRepository.findById(nowApplieOrderId);
        applieOrder.setIsOver(category);
        masterService.updateOrder(applieOrder);
        return ReturnModelAndView.returnSuccess("applie_order_list");
    }

    @RequestMapping(value = "/transaction_create_after",method = RequestMethod.POST)
    public ModelAndView createTransactions(@ModelAttribute TransactionPost transactionPost){
        getMaster();
        masterService.createTransaction(transactionPost);
        return ReturnModelAndView.returnSuccess("applie_order_list");
    }
    @Transactional
    @RequestMapping(value = "/upfiles",method = RequestMethod.POST)
    public JsonEntity upFiles(@RequestParam Long applieOrderId, @RequestParam("file") MultipartFile[] fileArray) throws Exception{
        getMaster();
        Long carId=new Date().getTime();
        ApplieOrder applieOrder= applieOrderRepository.findById(applieOrderId);
        Long userId=applieOrder.getUserId();
        MultipartFile file;
        String imgs="";
//        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        for (int i=0;i<fileArray.length;i++) {
            file=fileArray[i];
            String fileNameOrginal = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileNameOrginal)) {
                if (fileNameOrginal.substring(fileNameOrginal.length() - 3, fileNameOrginal.length()).equals("jpg")) {
                    String fileName = file.getOriginalFilename();
                    // 获取文件的后缀名
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));

                    // 解决中文问题，liunx下中文路径，图片显示问题
                    fileName = UUID.randomUUID() + suffixName;
                    fileName = fileName.replaceAll("-", "");

                    File f = new File("./mycar2w-web/src/main/resources/static/images/" + fileName);

                    if (!f.exists()) {
                        f.createNewFile();//create file if not exist
                    }
                    System.out.println(fileName);
                    InputStream in = file.getInputStream();
                    OutputStream out = new FileOutputStream(f);
                    int len;
                    byte[] bs = new byte[1024];
                    while ((len = in.read(bs)) != -1) {
                        out.write(bs, 0, len);
                    }
                    out.flush();
                    in.close();
                    out.close();
                    //System.out.println("存放图片文件的路径:" + realPath + "名称" + trueFileName);
                    // 转存文件到指定的路径
                    imgs = imgs + fileName + ",";
                }
            }
        }
        if(StringUtils.isNotBlank(imgs)){
            imgs=imgs.substring(0,imgs.length()-1);
        }
        for (int i=0;i<fileArray.length;i++) {
            file=fileArray[i];
            masterService.upFile(file,applieOrder,userId,carId,imgs);
        }
        return ReturnUtil.success("文件上传成功!");
    }

}
